package com.ledim.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.adapter.RoomDragListViewAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.RoomPlayVideoBean;
import com.ledim.bean.RoomPlaylistResponse;
import com.ledim.bean.base.BaseListResponse;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.itf.LedimOnItemClickListener;
import com.ledim.ledimview.DragListView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 编辑放映单
 */
public class EditPlayListsActivity extends LeDimBaseActivity
        implements LedimOnItemClickListener<List<RoomPlayVideoBean>> {

    public static final String ROOM_ID = "room_id";
    private DragListView mListView;
    private TextView mFinish;
    private TextView mSelectAll;
    private TextView mDelete;
    private ImageView mBack;
    private RoomDragListViewAdapter mAdapter;
    private ChatRoomBean mRoom;
    private View mNoPlayListLayout;
    private int mGoPlayNum = 0;
    private int mPlayNum = 0;
    private int count = 0;
    private ArrayList<RoomPlayVideoBean> mPlayLists = new ArrayList<RoomPlayVideoBean>();
    private ArrayList<RoomPlayVideoBean> mWaitPlayLists = new ArrayList<RoomPlayVideoBean>();
    private LoadingBar mLoadingBar;
    private boolean mIsSwap;
    private CommonDialogFragment mClearEditDialog;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_edit_play_lists;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        mRoom = (ChatRoomBean) getIntent().getSerializableExtra(ROOM_ID);
        mBack = (ImageView) findViewById(R.id.play_list_back_image);
        mFinish = (TextView) findViewById(R.id.edit_play_list_finish);
        mSelectAll = (TextView) findViewById(R.id.edit_play_list_select_all);
        mDelete = (TextView) findViewById(R.id.edit_play_list_delete);
        mListView = (DragListView) findViewById(R.id.edit_play_list_view);
        mNoPlayListLayout = findViewById(R.id.no_search);
        mLoadingBar = new LoadingBar(this);

        mNoPlayListLayout.setVisibility(View.GONE);
        mFinish.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mSelectAll.setOnClickListener(this);
        mDelete.setOnClickListener(this);

        getRoomPlayList();
    }

    /**
     * 获取播放列表
     */
    private void getRoomPlayList() {
        LedimApiServiceUtils.getRoomPlayList(mRoom.roomId, new LedimHttpObserver<RoomPlaylistResponse>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(RoomPlaylistResponse roomPlaylistResponse) {
                super.onNext(roomPlaylistResponse);
                if (roomPlaylistResponse.success) {
                    mWaitPlayLists.clear();
                    mWaitPlayLists.addAll(roomPlaylistResponse.data);
                    mDelete.setEnabled(mWaitPlayLists.size() > 0);
                    if (mRoom.status == 1) {//
                        for (int i = 0; i < mWaitPlayLists.size(); i++) {
                            if (mWaitPlayLists.get(i).play_status == 0) {
                                mWaitPlayLists.get(i).play_status = -1;
                                break;
                            }
                        }
                    }
                    if (mWaitPlayLists.size() != 0) {
                        mNoPlayListLayout.setVisibility(View.GONE);
                        if (mAdapter == null) {
                            mAdapter =
                                    new RoomDragListViewAdapter(EditPlayListsActivity.this, EditPlayListsActivity.this, mWaitPlayLists);
                            mListView.setAdapter(mAdapter);
                        } else {
                            mAdapter.setDatas(mWaitPlayLists);
                        }
                        //在这里设置监听，防止冲突Item的点击和拖拽的冲突
                        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position,
                                                    long id) {
                                if (mWaitPlayLists.get(position).play_status ==
                                        ConstantUtil.PlayState.wait) {
                                    mAdapter.getSelectEpisodes((ImageView) view.findViewById(R.id.item_drag_check), position);
                                }
                            }
                        });
                        //设置拖拽交换数据
                        mListView.setExchangeDataListener(new DragListView.ExchangeDataListener() {
                            public void setExchangeData(int from, int to) {
                                if (mWaitPlayLists.get(from).play_status == 0 &&
                                        mWaitPlayLists.get(to).play_status == 0) {
                                    if (from < to) {
                                        for (int i = from; i < to; i++) {
                                            Collections.swap(mWaitPlayLists, i, i + 1);
                                            mIsSwap = true;
                                        }

                                    } else if (from > to) {
                                        for (int i = from; i > to; i--) {
                                            Collections.swap(mWaitPlayLists, i, i - 1);
                                            mIsSwap = true;
                                        }
                                    }
                                    mAdapter.notifyDataSetChanged();
                                }
                            }
                        });
                    } else {
                        mNoPlayListLayout.setVisibility(View.VISIBLE);
                        mAdapter.setDatas(mWaitPlayLists);
                    }
                }
            }
        });
    }

    /**
     * @param playlists
     *         删除列表数据
     */
    private void deleteRoomPlayList(ArrayList<RoomPlayVideoBean> playlists) {
        JSONArray itemJSONArray = new JSONArray();
        for (int i = 0; i < playlists.size(); i++) {
            itemJSONArray.put(playlists.get(i).id);
        }
        LedimApiServiceFactory.createService(ApiService.class)
                              .deleteRoomPlayList(mRoom.roomId, itemJSONArray.toString())
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseListResponse<RoomPlayVideoBean>>() {

                                 @Override
                                 public void onError(Throwable e) {

                                 }

                                 @Override
                                 public void onNext(BaseListResponse<RoomPlayVideoBean> data) {
                                     if (data.success) {
                                         mAdapter.mSelectionMap.clear();
                                         for (int i = 0; i < data.data.size(); i++) {
                                             mAdapter.mSelectionMap.put(i, false);
                                         }
                                         mAdapter.setDatas(data.data);
                                         // getRoomPlayList();
                                         ToastUtil.toast("好了，大王！");
                                         mDelete.setText("删除");
                                         mDelete.setBackgroundResource(R.drawable.rect_round_start_play_bg);
                                         mSelectAll.setText("全选");
                                     }
                                 }
                             });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_list_back_image:
                finish();
                break;
            case R.id.edit_play_list_finish:
                if (mIsSwap) {
                    setRoomPlaylistSort(mRoom.roomId, mWaitPlayLists);
                } else {
                    finish();
                }
                break;
            case R.id.edit_play_list_select_all:
                count = 0;
                for (int i = 0; i < mWaitPlayLists.size(); i++) {
                    if (mWaitPlayLists.get(i).play_status == 0) {
                        count++;
                    }
                }
                if (count != 0) {
                    mAdapter.mSelectedEpisodes.clear();
                    if (mSelectAll.getText().equals("全选")) {
                        getWaitPlaylists();
                        mAdapter.notifyDataSetChanged();
                        mDelete.setText("删除（" + mGoPlayNum + "）");
                        mDelete.setBackgroundResource(R.drawable.rect_round_delete_play_list_bg);
                        mSelectAll.setText("取消");
                    } else if (mSelectAll.getText().equals("取消")) {
                        for (int i = 0; i < mWaitPlayLists.size(); i++) {
                            if (mWaitPlayLists.get(i).play_status == ConstantUtil.PlayState.wait) {
                                mAdapter.mSelectionMap.put(i, false);
                                mAdapter.mSelectedEpisodes.remove(mWaitPlayLists.get(i));
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        mDelete.setText("删除");
                        mSelectAll.setText("全选");
                        mDelete.setBackgroundResource(R.drawable.rect_round_start_play_bg);
                    }
                }
                break;
            case R.id.edit_play_list_delete:
                if (mAdapter.mSelectedEpisodes != null && !mAdapter.mSelectedEpisodes.isEmpty()) {
                    showClearDialog();
                }
                break;
        }
    }

    /**
     * 二次确认清除缓存弹窗
     */
    private void showClearDialog() {
        if (mClearEditDialog == null) {
            mClearEditDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, "清除选中的放映单：除秽之刃，斩！", "确定", "取消", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            if (mPlayLists.size() > 0) {
                                deleteRoomPlayList(mPlayLists);
                                mPlayLists.clear();
                                mAdapter.mSelectedEpisodes.clear();
                            }
                        }

                        @Override
                        public void onClickNegative(View view) {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
        }
        mClearEditDialog.showDialog(getSupportFragmentManager());
    }

    //获取等待播放的数据个数
    private void getWaitPlaylists() {
        mGoPlayNum = 0;
        mPlayLists.clear();
        for (int i = 0; i < mWaitPlayLists.size(); i++) {
            if (mWaitPlayLists.get(i).play_status == ConstantUtil.PlayState.wait) {
                mAdapter.mSelectionMap.put(i, true);
                mAdapter.mSelectedEpisodes.add(mWaitPlayLists.get(i));
                mPlayLists.add(mWaitPlayLists.get(i));
                mGoPlayNum++;
            }
        }
    }

    /**
     * 修改放映厅播放列表排序
     */
    @SuppressLint("InflateParams")
    private void setRoomPlaylistSort(String roomId, ArrayList<RoomPlayVideoBean> roomPlayListBeen) {

        String playListStr = null;
        try {
            int j = 0;
            JSONArray array = new JSONArray();
            for (int i = roomPlayListBeen.size() - 1; i >= 0; i--) {
                JSONObject obj1 = new JSONObject();
                obj1.put("playlist", roomPlayListBeen.get(i).id);
                obj1.put("sort", (j++) + "");
                array.put(obj1);
            }
            playListStr = array.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mLoadingBar.show();
        //进行网络请求
        LedimApiServiceFactory.createService(ApiService.class)
                              .modifyRoomPlaylistSort(roomId, playListStr)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseListResponse<RoomPlayVideoBean>>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     mLoadingBar.dismiss();
                                     ToastUtil.toast(e.getMessage());
                                     LogUtil.e(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(
                                         BaseListResponse<RoomPlayVideoBean> playlistBaseResultDataInfo) {
                                     super.onNext(playlistBaseResultDataInfo);
                                     mLoadingBar.dismiss();
                                     if (playlistBaseResultDataInfo != null) {
                                         if (playlistBaseResultDataInfo.success) {
                                             //成功
                                             ToastUtil.toast("好了，大王！");
                                             finish();
                                         } else {
                                             ToastUtil.toast(playlistBaseResultDataInfo.message);
                                         }
                                     }
                                 }
                             });

    }

    @Override
    public void onItemClick(int position, List<RoomPlayVideoBean> item, View v) {
        mPlayLists.clear();
        mPlayLists.addAll(item);
        if (mPlayLists.size() > 0) {
            mPlayNum = 0;
            for (int i = 0; i < mWaitPlayLists.size(); i++) {
                if (mWaitPlayLists.get(i).play_status == 0) {
                    mPlayNum++;
                }
            }
            mDelete.setText("删除（" + mPlayLists.size() + "）");
            mDelete.setBackgroundResource(R.drawable.rect_round_delete_play_list_bg);
            if (mPlayLists.size() == mPlayNum) {
                mSelectAll.setText("取消");
            } else {
                mSelectAll.setText("全选");
            }

        } else {
            mDelete.setText("删除");
            mDelete.setBackgroundResource(R.drawable.rect_round_start_play_bg);
        }
    }
}
